package com.capgemini.scaffold.utils;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ShuHao.Wen
 * @since 2022/10/21
 * 缓存
 */
@Component
public class MapCache {

    /**
     * 默认缓存容量
     */
    private static final int INITIAL_CAPACITY = 1024;

    /**
     * 缓存容器
     */
    private final Map<String, Object> cachePool;

    /**
     * 定时器  用来控制 缓存的超时时间
     */
    private final ScheduledExecutorService executorService;

    // 初始容量
    public MapCache(int initialCapacity) {
        cachePool = new ConcurrentHashMap<>(initialCapacity);
        // 延迟之后执行任务/定期执行任务  线程数量
        executorService = new ScheduledThreadPoolExecutor(2);
    }

    public MapCache() {
        this(INITIAL_CAPACITY);
    }

    /**
     * 设置缓存 无过期时间
     *
     * @param key   键
     * @param value 值
     */
    public void put(String key, Object value) {
        cachePool.put(key, value);
    }

    /**
     * 设置缓存 有过期时间
     *
     * @param key     键
     * @param value   值
     * @param timeout 过期时间
     */
    public void put(String key, Object value, int timeout) {
        cachePool.put(key, value);
        executorService.schedule(() -> remove(key), timeout, TimeUnit.SECONDS);
    }

    /**
     * 读取缓存
     *
     * @param key 键
     * @return 返回值
     */
    public Object get(String key) {
        return cachePool.get(key);
    }

    /**
     * 获取所有key
     *
     * @return 获取所有key
     */
    public Set<String> getKeys() {
        return cachePool.keySet();
    }

    /**
     * 获取当前缓存所有内容
     * @return
     */
    public Map<String ,Object> allCache(){
        return cachePool;
    }

    /**
     * 判断缓存是否包含key
     * @param key key
     * @return 是否包含
     */
    public boolean containsKey(String key){
        return cachePool.containsKey(key);
    }


    /**
     * 获取当前缓存大小
     *
     * @return 缓存大小
     */
    public int size() {
        return cachePool.size();
    }

    /**
     * 根据key删除缓存
     *
     * @param key key
     */
    public void remove(String key) {
        cachePool.remove(key);
    }

    /**
     * 清空缓存
     */
    public void clean() {
        if (size() > 0) {
            cachePool.clear();
        }
    }

}


